/*
 * Copyright (c) 2020 Taner Sener
 *
 * This file is part of FlutterFFmpeg.
 *
 * FlutterFFmpeg is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FlutterFFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with FlutterFFmpeg.  If not, see <http://www.gnu.org/licenses/>.
 */

import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

class FileUtil {
  static Future<Directory?> get documentsDirectory async {
    if (Platform.isIOS) {
      return (await getApplicationDocumentsDirectory());
    }
    return (await getExternalStorageDirectory());
  }

  static Future<Directory?> get tempDirectory async {
    if (Platform.isIOS) {
      return (await getTemporaryDirectory());
    }
    return (await getExternalStorageDirectory());
  }

  static deleteTempDirectoryCache({String? prefix}) async {
    await _delDir((await FileUtil.tempDirectory)!, prefix: prefix);
    /// await _loadCache();
  }

  // 递归方式删除目录
  static Future<Null> _delDir(FileSystemEntity file, {String? prefix}) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await _delDir(child, prefix: prefix);
      }
    } else {
      if (prefix!=null) {
        if (file.path.contains(prefix)) {
          print('---😆😆递归方式删除文件, file:$file 😆😆---');
          await file.delete();
        }
      } else {
        await file.delete();
      }
    }
  }

  static loadCache() async {
    tempDirectory.then((value) {
      value?.list(followLinks: false, recursive: true).listen((file) {
        print('---😆😆缓存文件的路径, file.path:${file.path} 😆😆---');
      });
    });
  }

  // 循环计算文件的大小（递归）
  Future<double> getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children) {
        total += await getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }
}
